<?php

namespace App\Http\Middleware;

use Closure;
use Dcat\Admin\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class LogAccessMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        // 获取请求的相关信息
        $method = $request->method();
        $url = $request->fullUrl();
        $ip = $request->ip();
        $payload = $request->input();
        if (isset($payload['password'])) {
            unset($payload['password']);
        }
        try {
            $userId = auth('jwt')->id();
        } catch (\Exception $e) {
            $userId = 0;
        }

        $adminPrefix = config('admin.route.prefix');
        if ($request->is('api/*')) {
            $channel = 'api';
        } else if ($request->is("{$adminPrefix}/*")) {
            $channel = 'admin';
            if (Admin::user()) {
                $userId = Admin::user()->id;
            } else {
                $userId = 0;
            }
        } else if ($request->is("dashboard/*")) {
            $channel = 'dash';
            $userId = auth('dash')->id() ?? 0;
        } else {
            $channel = 'web';
        }

        // 记录日志
        Log::channel($channel)->info(json_encode([
            'url' => $url,
            'method' => $method,
            'ip' => $ip,
            'time' => date('Y-m-d H:i:s', time()),
            'user' => $userId,
            'payload' => $payload,
        ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));

        return $next($request);
    }
}
